package com.bojx.cms.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

import org.apache.log4j.Logger;

import com.jfinal.kit.PropKit;

public class UploadUtil {

	private static Logger logger=Logger.getLogger(UploadUtil.class);
	static{
		PropKit.use("/properties/appconfig.properties");
	}
	public static String uploadImage(InputStream in,String extension) throws Exception {
		
		try {
			
			String fileName = UUIDUtil.getRandomSn()+ "."+extension;
			String uploadPath=PropKit.get("IMG_UPLOAD_PATH");
			String accessPath = PropKit.get("IMG_ACCESS_PATH");
			String folder=DateUtil.dateFormat(new Date(), "yyyyMMdd");
			File dir=new File(uploadPath+ "/"+folder);
			if (!dir.exists()  && !dir.isDirectory()){       
			    dir.mkdir();    
			}  
			String imgFileName=uploadPath+"/"+folder+"/"+fileName;
			OutputStream out=new FileOutputStream(new File(imgFileName));
			IOUtils.copy(in, out);
			out.close();
			//判断图片是否写到磁盘上了
			File image=new File(imgFileName);
			if(!image.exists()){
				throw new Exception("图片上传失败");
			}
			String url="http://"+accessPath+"/"+folder+"/"+fileName;
			return url;
		} catch (IOException e1) {
			logger.error("Upload image error.", e1);
			throw new Exception("上传失败", e1);

		} catch (Exception e2) {
			logger.error("Upload image error.", e2);
			throw new Exception("上传失败", e2);

		}
	
	}
	
public static String uploadFile(InputStream in,String extension) throws Exception {
		
		try {
			
			String fileName = UUIDUtil.getRandomSn()+ "."+extension;
			String uploadPath=PropKit.get("FILE_UPLOAD_PATH");
			String accessPath = PropKit.get("FILE_ACCESS_PATH");
			String folder=DateUtil.dateFormat(new Date(), "yyyyMMdd");
			File dir=new File(uploadPath+ "/"+folder);
			if (!dir.exists()  && !dir.isDirectory()){       
			    dir.mkdir();    
			}  
			String imgFileName=uploadPath+"/"+folder+"/"+fileName;
			OutputStream out=new FileOutputStream(new File(imgFileName));
			IOUtils.copy(in, out);
			out.close();
			//判断图片是否写到磁盘上了
			File image=new File(imgFileName);
			if(!image.exists()){
				throw new Exception("文件上传失败");
			}
			String url="http://"+accessPath+"/"+folder+"/"+fileName;
			return url;
		} catch (IOException e1) {
			logger.error("Upload file error.", e1);
			throw new Exception("上传失败", e1);

		} catch (Exception e2) {
			logger.error("Upload file error.", e2);
			throw new Exception("上传失败", e2);

		}
	
	}
	
	
	
	
	
	
	
	
	
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}